package base.thread_demo.demo10;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ThreadLocal 绑定的是跟线程范围内的数据
 *
 * t1线程 通过 ThreadLocal.set(Object)设置的值,只能t1线程通过 ThreadLocal.get()方式获取,t2获取不到
 */
public class SequenceNumberTest {
    private static final Logger log = LoggerFactory.getLogger(SequenceNumberTest.class);

    //通过匿名内部类覆盖ThreadLocal的initialValue()方法，指定初始值
    //等号右边：匿名类，实现ThreadLocal
    //等号左边：是多态赋值,ThreadLocal类型引用指向子类对象
    private static ThreadLocal<Integer> local = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 1;
        }
    };

    public static void main(String[] args) {
        // 启动3个线程
//        for (int i = 0; i < 3; i++) {
//            new Thread(()->{
//                // 每个线程内部获取5次连续整数
//                for (int j = 0; j < 5; j++) {
//                    Integer num = local.get();
//                    log.info("{} -> {}", Thread.currentThread().getName(), num);
//                    local.set(num +1);//给local设置下一位整数值
//                }
//            },"t"+i).start();
//        }
        new Thread(()->{
            // 每个线程内部获取3次连续整数
            for (int j = 0; j < 3; j++) {
                Integer num = local.get();
                log.info("{} -> {}", Thread.currentThread().getName(), num);
                local.set(num +1);//给local设置下一位整数值
            }
        },"t1").start();
        new Thread(()->{
            // 每个线程内部获取3次连续整数
            for (int j = 0; j < 3; j++) {
                Integer num = local.get();
                log.info("{} -> {}", Thread.currentThread().getName(), num);
                local.set(num +1);//给local设置下一位整数值
            }
        },"t2").start();
        new Thread(()->{
            // 每个线程内部获取3次连续整数
            for (int j = 0; j < 3; j++) {
                Integer num = local.get();
                log.info("{} -> {}", Thread.currentThread().getName(), num);
                local.set(num +1);//给local设置下一位整数值
            }
        },"t3").start();
    }
}


